package com.uniledger.exchange.wallet;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.orhanobut.logger.Logger;
import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.login.Admin;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;

import org.stellar.sdk.KeyPair;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.github.novacrypto.bip39.MnemonicValidator;
import io.github.novacrypto.bip39.SeedCalculator;
import io.github.novacrypto.bip39.Validation.InvalidChecksumException;
import io.github.novacrypto.bip39.Validation.InvalidWordCountException;
import io.github.novacrypto.bip39.Validation.UnexpectedWhiteSpaceException;
import io.github.novacrypto.bip39.Validation.WordNotFoundException;
import io.github.novacrypto.bip39.wordlists.English;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import mabbas007.tagsedittext.TagsEditText;

public class RestoreActivity extends BaseActivity
        implements TagsEditText.TagsEditListener {


    public static void start(Activity activity) {
        Intent intent = new Intent(activity, RestoreActivity.class);
        activity.startActivity(intent);
    }

    @BindView(R.id.editText)
    EditText editText;

    @BindView(R.id.button)
    Button restore;

    @BindString(R.string.restore_bar_title)
    String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restore);
        editText.setText("");
    }

    @Override
    public void getParams() {

    }

    @Override
    public void initBar() {
        super.initBar();
        toolbar.setTitle(title);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.btn_close_normal);
    }

    @OnClick(R.id.button)
    void restore() {
        String mnemonic = editText.getText().toString();
        //首先计算是否为12个单词
        List<String> list = Arrays.asList(mnemonic.split("\\s+"));
        if (list.size() == 12) {
            try {
                MnemonicValidator
                        .ofWordList(English.INSTANCE)
                        .validate(mnemonic);
                new KeyTask().execute(mnemonic);
            } catch (UnexpectedWhiteSpaceException e) {
                Logger.d(e.getMessage());
            } catch (InvalidWordCountException e) {
                Logger.d(e.getMessage());
            } catch (InvalidChecksumException e) {
                Logger.d(e.getMessage());
            } catch (WordNotFoundException e) {
                Logger.d(e.getMessage());
                //e.getSuggestion1()
                //e.getSuggestion2()
            }
        }


    }

    @Override
    public void onTagsChanged(Collection<String> collection) {

    }

    @Override
    public void onEditingFinished() {

    }

    class KeyTask extends AsyncTask<String, Integer, WalletKey> {
        @Override
        protected WalletKey doInBackground(String... strings) {
            String mnemonic = strings[0];
            //助记词+口令
            final byte[] seed = new SeedCalculator().calculateSeed(mnemonic, "");
            KeyPair keyPair = KeyPair.fromSecretSeed(seed);
            //保存密钥对
            OkSingleton.getInstance().setSourceKeyPair(keyPair);

            return new WalletKey(mnemonic, keyPair.getAccountId());
        }

        @Override
        protected void onPostExecute(WalletKey walletKey) {
            super.onPostExecute(walletKey);
            Map<String, String> params = new HashMap<>();
            params.put("stellar_addr", walletKey.accountId);
            params.put("timestamp", System.currentTimeMillis() + "");
            params.put("nonce", System.currentTimeMillis() + "");
            params.put("sign", "");

            Api.getService().signIn(params)
                    .map(new Function<HttpResult<Admin>, HttpResult<Admin>>() {
                        @Override
                        public HttpResult<Admin> apply(HttpResult<Admin> adminHttpResult) throws Exception {
                            Admin admin = adminHttpResult.data;
                            admin.uid = 123;
                            admin.walletFlag = 3;
                            admin.isSignIn = true;

                            UniApp.getDb().adminDao().insert(admin);
                            OkSingleton.getInstance().setToken(admin.token);


                            //处理钱包数据
                            walletKey.uid = 123;
                            walletKey.isBackup = true;
                            walletKey.name = admin.firstName;
                            UniApp.getDb().keyDao().insert(walletKey);

                            OkSingleton.getInstance().setIssuingKeyPair(KeyPair.fromAccountId(admin.issuingAccountId));
                            OkSingleton.getInstance().setBaseKeyPair(KeyPair.fromAccountId(admin.baseAccountId));

                            return adminHttpResult;
                        }
                    })
                    .compose(RxSchedulers.io_main())
                    .compose(RxProgress.applyProgressBar(RestoreActivity.this))
                    .subscribe(new Consumer<HttpResult<Admin>>() {
                        @Override
                        public void accept(HttpResult<Admin> httpResult) throws Exception {
                            HomeActivity.start(RestoreActivity.this);
                            finish();
                        }
                    }, new RxException<>(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            ToastUtils.show(throwable.getMessage());
                        }
                    }));
        }
    }
}
